package com.jie.other.network

import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.os.Build
import androidx.core.app.NotificationCompat
import com.blankj.utilcode.util.Utils
import com.jie.other.R

/**
 * 带进度条的下载通知栏工具类
 */
object DownloadNotificationUtils {

    private const val CHANNEL_ID = "DOWNLOAD"
    private const val CHANNEL_NAME = "文件下载"
    private const val NOTIFICATION_ID = 0x111

    private val mManager: NotificationManager =
        Utils.getApp().getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

    /**
     * 显示通知栏
     */
    fun showNotify(progress : Int, max : Int){
        val notifyBuilder = getNotifyBuilder()
        notifyBuilder.setContentText("$progress%")
        notifyBuilder.setProgress(max, progress, false)
        mManager.notify(NOTIFICATION_ID, notifyBuilder.build())
    }

    /**
     * 取消通知栏
     */
    fun cancel(){
        mManager.cancel(NOTIFICATION_ID)
    }

    /**
     * 获取通知栏构建信息
     */
    private fun getNotifyBuilder() : NotificationCompat.Builder{
        val notificationBuilder = NotificationCompat.Builder(Utils.getApp(), CHANNEL_ID)
            .setSmallIcon(R.mipmap.other_ic_launcher)
            .setContentTitle("文件下载中")
            .setOnlyAlertOnce(true)
            .setAutoCancel(true)
        // Android 8.0适配
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
            // 创建通道
            val notificationChannel =
                NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT)
            mManager.createNotificationChannel(notificationChannel)
            // 设置通道
            notificationBuilder.setChannelId(CHANNEL_ID)
        }
        return notificationBuilder
    }

}